<template>
  <div class="hello">
    <h2>{{ msg }}</h2>
    <input type="text" @keyup.enter="addFeature" />
    <div v-for="feature in features" :key="feature.id">
      {{ feature.name }}
    </div>
    <div>新特性总数：{{ count }}</div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Emit, Watch } from "vue-property-decorator";
import axios from "axios";

interface Feature {
  id: number;
  name: string;
}

interface Result<T> {
  data: T;
}

function getDate<T>(): Promise<Result<T>> {
  const data: any = [
    { id: 1, name: "类型注解" },
    { id: 2, name: "类型检测" },
    { id: 3, name: "类型审核" },
  ];
  return Promise.resolve<Result<T>>({ data });
}

// Component 把后面的代码转换成为vue的配置对象，并把它变成vue的构造函数
@Component
export default class HelloWorld extends Vue {
  @Prop({ type: String, required: true })
  // 感叹号！ 明确赋值的断言
  private msg!: string;

  // 属性相当于data选项
  private features: Feature[] = [];

  constructor() {
    super();
  }

  async mounted() {
    console.log("HelloWorld组件已挂载");
    this.features = (await getDate<Feature[]>()).data;
    const res = await axios.get<Feature[]>("/api/getFeature");
    this.features = res.data;
  }

  @Watch('msg', {deep: true})

  @Emit()
  private addFeature(e: any) {
      const f = {id: this.features.length + 1, name: e.target.value}
    this.features.push(f);
    e.target.value = "";
    return f
  }

  get count() {
    return this.features.length;
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>
